package com.nosnow.msm.controller;

import com.nosnow.common.utils.R;
import com.nosnow.msm.service.MsmService;
import com.nosnow.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author by bingHeng
 * @version 1.0
 * @Create 2020/4/21 23:29
 */

@RestController
@RequestMapping("/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("sendMsm/{phone}")
    public R sendMsm(@PathVariable String phone) {
        try {
            // 1. 验证码5分钟内有效，从redis中获取, 取到验证码，直接返回，否则发送
            String code = redisTemplate.opsForValue().get(phone);
            if(!StringUtils.isEmpty(code)) {
                return R.ok();
            }

            // 2. 生成随机数
            Map<String, Object> param = new HashMap<>();
            code = RandomUtil.getFourBitRandom();
            param.put("code", code);

            // 3. 发送短信
            boolean flog = msmService.send(param, phone);
            if(flog) {
                // 3.1 发送成功，把发送成功的验证码放到redis里面, 并设置5分钟有效
                redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
                return R.ok();
            } else {
                return R.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
}
